// AwardsServiceImpl.java - 调用领域对象的业务逻辑
package com.elm.service.impl;

import com.elm.mapper.UserMapper;
import com.elm.po.Awards;
import com.elm.mapper.AwardsMapper;
import com.elm.service.AwardsService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class AwardsServiceImpl implements AwardsService {

    @Autowired
    private AwardsMapper awardsMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Awards> getAwards() {
        return awardsMapper.getAwards();
    }

    private String getCurrentUserName() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    @Override
    public boolean updateAwards(Long id, BigDecimal recharge_amount, BigDecimal award_amount) {
        // 充血模型：先获取领域对象，然后调用其业务方法
        Awards awards = findAwardsById(id);
        if (awards == null) {
            return false;
        }

        awards.updateAwardsInfo(recharge_amount, award_amount);
        String token = (String) request.getAttribute("token");
        int userId = userMapper.getUserIdByName(getCurrentUserName());

        return awardsMapper.updateAwards(id, awards.getRecharge_amount(), awards.getAward_amount());
    }

    @Override
    public boolean addAwards(Awards awards) {
        // 充血模型：在添加前进行业务验证
        awards.validateForCreation();
        Long id = awards.getId();
        BigDecimal recharge_amount = awards.getRecharge_amount();
        BigDecimal award_amount = awards.getAward_amount();
        return awardsMapper.insertAwards(id, recharge_amount, award_amount);
    }

    @Override
    public boolean deleteAwards(Long id) {
        return awardsMapper.deleteAwards(id);
    }

    // 辅助方法：根据ID查找奖励（在实际项目中可能需要在Mapper中添加此方法）
    private Awards findAwardsById(Long id) {
        List<Awards> allAwards = awardsMapper.getAwards();
        return allAwards.stream()
                .filter(award -> award.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
}